package com.guet.niit.Login.controller.login;

import com.guet.niit.Login.pojo.Account;
import com.guet.niit.Login.pojo.Agent;
import com.guet.niit.Login.pojo.People;
import com.guet.niit.Login.pojo.User;
import com.guet.niit.Login.service.LoginService;
import com.guet.niit.Login.service.UserService;
import com.guet.niit.util.SnowFlakeUtil;
import com.sun.javafx.stage.StageHelper;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;

import java.io.IOException;
import java.util.List;

public class LoginFxController {
    @FXML
    Button login;

    @FXML
    TextField username;

    @FXML
    PasswordField password;

    @FXML
    ChoiceBox type;

    @FXML
    Button register;

    /**
     * 用户登录
     * @param mouseEvent
     */
    public void userLogin(MouseEvent mouseEvent) {
        LoginService loginService = new LoginService();
        //获取输入框的账号和密码
        String usernameText = username.getText();
        String passwordText = password.getText();
        try {
            //获取用户类型
            Object value = type.getValue();
            String type = value.toString();
            //调用service层获取存储在数据库的账号和密码
            if (type.equals("用户")){
                //查询用户表
                List<User> userLoginList = loginService.userCheckLogin();
                compareUser(userLoginList,usernameText,passwordText);
            }else {
                //查询代理商表
                List<Agent> agentLoginList = loginService.agentCheckLogin();
                compareUser(agentLoginList,usernameText,passwordText);
            }
        } catch (NullPointerException e) {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setHeaderText(null);
            alert.setContentText("请选择用户类型!");
            alert.showAndWait();
        }
    }

    /**
     * 比较输入的账号密码和存储在数据库的账号密码
     * @param user
     * @param usernameText
     * @param passwordText
     */
    //使用泛型的上界通配符，传入的List为People或People的子类
    public void compareUser(List<? extends People> user, String usernameText, String passwordText){
        for (int i = 0; i < user.size(); i++) {
            if (usernameText.equals(user.get(i).getUsername()) && passwordText.equals(user.get(i).getPassword())){
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setHeaderText(null);
                alert.setContentText("登陆成功！");
                alert.showAndWait();
                System.out.println(user.get(i));
                //获取登录用户的id
                Long id = user.get(i).getId();
                String userId = id.toString();
                //将用户id设置为当前线程名
                Thread.currentThread().setName(userId);
                System.out.println(Thread.currentThread().getName());
                //获取用户的登陆类型
                Object value = type.getValue();
                String type = value.toString();
                //关闭登录窗口
                ObservableList<Stage> stageList = StageHelper.getStages();
                stageList.get(0).close();
                //根据用户类型打开新窗口
                enterStage(type,usernameText);
                return;
            }
        }
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setHeaderText(null);
        alert.setContentText("用户名或密码输入错误!");
        alert.showAndWait();
    }

    /**
     * 根据用户选择的用户类型进入相应的界面
     */
    public void enterStage(String type,String usernameText){
        if (usernameText.equals("admin")){
            type = "管理员";
        }
        switch (type){
            case "用户":
                Stage userStage = new Stage();
                userStage.setTitle("充电桩用户系统");
                //引用fxml样式
                Parent userRoot = null;
                try {
                    userRoot = FXMLLoader.load(getClass().getResource("/fxml/user/userMenu.fxml"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //设置一个Scene
                Scene userScene = new Scene(userRoot);
                //Scene与Stage关联
                userStage.setScene(userScene);
                //设置窗口样式
                userStage.setHeight(640);
                userStage.setWidth(345);
                userStage.getIcons().add(new Image("img/battery.jpg"));
                userStage.setResizable(false);
                userStage.show();
                break;
            case "代理商":
                Stage agentStage = new Stage();
                agentStage.setTitle("充电桩代理商系统");
                //引用fxml样式
                Parent agentRoot = null;
                try {
                    agentRoot = FXMLLoader.load(getClass().getResource("/fxml/agent/agentMenu.fxml"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //设置一个Scene
                Scene agentScene = new Scene(agentRoot);
                //Scene与Stage关联
                agentStage.setScene(agentScene);
                //设置窗口样式
                agentStage.setHeight(600);
                agentStage.setWidth(345);
                agentStage.getIcons().add(new Image("img/battery.jpg"));
                agentStage.setResizable(false);
                agentStage.show();
                break;
            default:
                Stage adminStage = new Stage();
                adminStage.setTitle("充电桩管理系统");
                //引用fxml样式
                Parent adminRoot = null;
                try {
                    adminRoot = FXMLLoader.load(getClass().getResource("/fxml/admin/adminMenu.fxml"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //设置一个Scene
                Scene adminScene = new Scene(adminRoot);
                //Scene与Stage关联
                adminStage.setScene(adminScene);
                //设置窗口样式
                adminStage.setHeight(438);
                adminStage.setWidth(710);
                adminStage.getIcons().add(new Image("img/battery.jpg"));
                adminStage.setResizable(false);
                adminStage.show();
                break;
        }
    }

    /**
     * 注册新用户
     * @param mouseEvent
     */
    public void userRegister(MouseEvent mouseEvent) {
        LoginService loginService = new LoginService();
        //获取注册用户的id
        SnowFlakeUtil snowFlakeUtil = new SnowFlakeUtil(2, 3);
        long userId = snowFlakeUtil.nextId();
        //获取输入框的账号和密码
        String usernameText = username.getText();
        String passwordText = password.getText();
        try {
            //获取用户类型
            Object value = type.getValue();
            String type = value.toString();
            //调用service层存储用户输入的账号密码到数据库
            if (type.equals("用户")){
                //将用户信息装入实体类
                User registerUser = new User(userId,usernameText,passwordText);
                Double balance = 0.00;
                String phone = "";
                Account registerAccount = new Account(userId, balance, phone);
                //common_user表插入数据
                loginService.userRegister(registerUser);
                //account表插入数据
                UserService userService = new UserService();
                userService.AddAccount(registerAccount);
//            compareUser(userLoginList,usernameText,passwordText);
            }else {
                //将代理商信息装入实体类
                Agent registerAgent = new Agent(userId, usernameText, passwordText);
                //agent_user表插入数据
                loginService.agentRegister(registerAgent);
//            compareUser(agentLoginList,usernameText,passwordText);
            }
        } catch (NullPointerException e) {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setHeaderText(null);
            alert.setContentText("请选择用户类型!");
            alert.showAndWait();
        }
    }
}
